package _interview150;

import java.util.ArrayList;
import java.util.List;

/**
 * 52. N 皇后 II
 */
public class No52 {
    private List<List<Integer>> ans;
    private List<Integer> path;
    private int n;

    public int totalNQueens(int n) {
        ans = new ArrayList<>();
        path = new ArrayList<>();
        this.n = n;
        dfs(0);
        return ans.size();
    }

    private void dfs(int i) {
        if (i == n) {
            ans.add(new ArrayList<>(path));
            return;
        }

        for (int j = 0; j < n; j++) {
            if (!isValid(i, j)) continue;
            path.add(j);
            dfs(i + 1);
            path.remove(path.size() - 1);
        }
    }

    private boolean isValid(int i, int j) {
        for (int row = 0; row < path.size(); row++) {
            Integer column = path.get(row);
            if (row == i || column == j || row - column == i - j || row + column == i + j) return false;
        }
        return true;
    }
}
